package cn.kaiux.bigdata.homework.week05_06

import org.apache.hadoop.fs.Path
import scopt.OptionParser

import java.net.URI

/**
 * @author kaiux@foxmail.com
 * @date 2022/6/11 14:13
 */
object InvertedIndexOptionsParsing {

  def parse(args: Array[String]): InvertedIndexConfig = {

    val parser = new OptionParser[InvertedIndexConfig]("") {
      arg[String]("[source_path...] <target_path>")
        .unbounded()
        .action((u, c) => c.copy(URIs = c.URIs :+ new URI(u)))
    }
    parser.parse(args, InvertedIndexConfig()) match {
      case Some(config) =>
        config.validate()
        config
      case _ =>
        throw new RuntimeException("Failed to parse arguments")
    }
  }

  def main(args: Array[String]): Unit = {
    val config = parse(args)
    println(config)
    println(config.getPaths)
  }

}

case class InvertedIndexConfig(URIs: Seq[URI] = Seq.empty) {

  // 验证参数，路径必须大于2个（多个输入和一个输出）
  def validate(): Unit = {
    require(URIs.length >= 2, "Paths must be specified for source and target")
  }

  // 解析输入和输出路径
  def getPaths: (Seq[Path], Path) = {
    URIs.reverse match {
      case d :: s :: ts =>
        ((s :: ts).reverse.map(u => new Path(u)), new Path(d))
      case _ => throw new RuntimeException("Invalid paths")
    }
  }

}
